// 导入createRouter
import { createRouter, createWebHashHistory } from 'vue-router'
import useStore from '@/store'


// 导入路由组件
import Home from '@/views/Home/Home.vue'
import Message from '@/components/XtxMessage'
// 定义路由规则
const router = createRouter({
    scrollBehavior: () => {
        return {
            top: 0,
        }
    },
    history: createWebHashHistory(),
    routes: [
        {
            path: '/',
            component: () => import('@/views/Layout/Layout.vue'),
            children: [
                {
                    path: '',
                    component: Home
                },
                // 分类页
                {
                    path: 'category/:id',
                    component: () => import('@/views/category/category.vue')
                },
                // 详情页
                {
                    path: 'product/:id',
                    component: () => import('@/views/Goods/Goods.vue')
                },
                // 购物车页
                {
                    path: '/cart',
                    component: () => import('@/views/Cart/Cart.vue')
                },
                // 结算页
                {
                    path: '/member/checkout',
                    component: () => import('@/views/Member/checkout.vue')
                },
                // 支付页
                {
                    path: '/member/pay',
                    component: () => import('@/views/Member/Pay.vue')
                },
                // 支付完成页
                {
                    path: '/member/callback',
                    component: () => import('@/views/Member/callback.vue')
                }
            ]
        },
        {
            path: '/login',
            component: () => import('@/views/Login/Login.vue')
        },
        {
            path: '/login/callback',
            component: () => import('@/views/Login/Callback.vue')
        },
        {
            path: '/demo',
            component: () => import('@/views/demo/demo.vue')
        }
    ]
})

// const path1 = ['/member/checkout']

// 路由前置守卫
router.beforeEach((to, from, next) => {
    const { cart } = useStore()
    // 判断是否登录
    if (cart.isLogin) {
        next()
    } else {
        if (to.path === '/member/checkout') {
            next({
                path: '/login',
                query: {
                    redirectUrl: to.fullPath
                }
            })
            Message.warning('请先登录')
        } else {
            next()
        }
    }
})

export default router